#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2024/11/10 11:41
# @Author  : Tom_zc
# @FileName: auto_config_repo.py
# @Software: PyCharm

"""
脚本流程：
1.过滤事件
2.准备环境
3.查询出差异点   增加的仓库/修改的仓库/(删除的仓库) ---> 删除的仓库这个不用考虑
4.创建仓库或者仓库
5.评论处理成功
"""

import os
import sys
import logging
import base64
import yaml

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, "utils"))

from utils.gitcode_helper import GitCodeHelper
from utils.parse_params import parse_repo_info_by_webhook_payload, parse_pr_user_by_webhook_payload
from utils.majun_helper import MaJunHelper
from utils.libing_helper import LiBingHelper

logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s  %(levelname)s:%(message)s")


class WorkFlow:
    success_comment = "Hello, [@{gitcode_id}](https://gitcode.com/{gitcode_id}), " \
                      "your submission has been successfully executed."
    failed_comment = "Hello, [@{gitcode_id}](https://gitcode.com/{gitcode_id}), " \
                     "the content you submitted failed to execute, please contact the [@openUBMC-robot]" \
                     "(https://gitcode.com/openUBMC-robot)."

    def __init__(self, owner, repo, pr_number, token, domain):
        self.gitcode_helper = GitCodeHelper(owner, repo, pr_number, token, domain)

    def comment(self, comment, pr_gitcode_id):
        self.gitcode_helper.create_comment({"body": comment.format(gitcode_id=pr_gitcode_id)})

    def parse_pr_info(self):
        repo_paths = list()
        repo_infos = list()
        pr_files = self.gitcode_helper.get_pr_files()
        for pr in pr_files:
            if pr["filename"].startswith("sigs/") and pr["filename"].endswith("/repo-info.yaml"):
                repo_paths.append(pr["filename"])
        for repo_path in repo_paths:
            resp = self.gitcode_helper.get_contents(repo_path)
            content = base64.b64decode(resp["content"]).decode("utf-8")
            repo_info = yaml.safe_load(content)
            repo_infos.extend(repo_info)
        return repo_infos

    def get_repo(self, repo_info):
        resp = self.gitcode_helper.get_repo(repo_info["name"])
        if str(resp.status_code).startswith("20"):
            return True
        return False

    def create_repo(self, repo_info, owner):
        body = {
            "name": repo_info["name"],
            "description": repo_info["description"],
            "auto_init": True,
            "public": 1
        }
        if repo_info["type"] != "public":
            body["private"] = True
            body["public"] = 0
        return self.gitcode_helper.create_repo(body, org=owner)

    def modify_repo(self, repo_info):
        body = {
            "name": repo_info["name"],
            "description": repo_info["description"],
            "private": not repo_info["type"] == "public"
        }
        return self.gitcode_helper.modify_repo(repo_info["name"], body)


def main():
    logging.info("=" * 20 + "start to auto config repo" + "=" * 20)
    token = os.getenv("gitcode_token")
    gitcode_api_domain = os.getenv("gitcode_api_domain")
    gitcode_domain = os.getenv("gitcode_domain")
    owner = os.getenv("owner") or "openUBMC"
    ma_jun_token = os.getenv("majun_token")
    ma_jun_domain = os.getenv("majun_domain")
    li_bing_appkey = os.getenv("libing_appkey")
    li_bing_account = os.getenv("libing_accountId")
    li_bing_domain = os.getenv("libing_domain")

    if not all([token, gitcode_api_domain, owner, ma_jun_token, ma_jun_domain, gitcode_domain, li_bing_domain,
                li_bing_appkey, li_bing_account]):
        logging.info("Lack of params, Please check.")

    _, repo, branch, pr_number, _ = parse_repo_info_by_webhook_payload()
    workflow = WorkFlow(owner, repo, pr_number, token, domain=gitcode_api_domain)
    pr_gitcode_id = parse_pr_user_by_webhook_payload()
    try:
        repo_infos = workflow.parse_pr_info()
        logging.info("parse the repo:{}".format(str(repo_infos)))
        # if not exist and create the repo, or try to modify the repo
        for repo_info in repo_infos:
            if not workflow.get_repo(repo_info):
                logging.info("create repo:{}".format(repo_info["name"]))
                workflow.create_repo(repo_info, owner)
                ma_jun = MaJunHelper(ma_jun_token, ma_jun_domain)
                ma_jun.add_repo(gitcode_domain, owner, repo_info["name"], private=repo_info["type"])
                li_bing = LiBingHelper(li_bing_account, li_bing_appkey, li_bing_domain)
                li_bing.add_repo(gitcode_domain, owner, repo_info["name"], private=repo_info["type"])
            else:
                logging.info("modify repo:{}".format(repo_info["name"]))
                workflow.modify_repo(repo_info)
        workflow.comment(workflow.success_comment, pr_gitcode_id)
    except Exception as e:
        # comment and done well
        logging.info("e:{}".format(e))
        workflow.comment(workflow.failed_comment, pr_gitcode_id)
    logging.info("=" * 20 + "end to auto config repo" + "=" * 20)


if __name__ == '__main__':
    main()
